var express = require('express');
var router = express.Router();
var expressWs = require('express-ws')(router);
var chatDao = require('./../dao/chat');
require('./../utils/common');

router.ws('/message', function (ws, req) {
  var par = paramAll(req);

  if (!par.friendphone || !par.userphone || !par.app_sid) {
    return ws.send(JSON.stringify({
      code: 0,
      msg: '参数不全!'
    }));
  }

  //查询用户历史记录
  chatDao.getOnlineChat(par, function (err, data) {
    if (err) {
      return ws.send(JSON.stringify({
        code: 0,
        msg: err
      }));
    }

    return ws.send(JSON.stringify({
      code: 1,
      data: data
    }));
  });

  ws.on('message', function (msg) {
    console.log(msg);
    par.msg = JSON.parse(msg);
    //将记录添加到数据库，并返回最新记录列表
    chatDao.saveOnlineChat(par.msg, function (err, data) {
      if (err) {
        return ws.send(JSON.stringify({
          code: 0,
          msg: err
        }));
      }

      return ws.send(JSON.stringify({
        code: 1,
        data: data
      }));
    });
  });
});

router.ws('/', function (ws, req) {
  console.log('测试');
  console.log(paramAll(req));
  
  ws.on('message', function (msg) {
    return ws.send(msg);
  });
});

module.exports = router;